package com.im.util;

import java.util.Random;

/**
 * @author wangxh
 * @ClassName: SerialNumberUtil
 * @Description:序列号生成器
 * @date 2017/5/31 10:08
 */
public class SerialNumberUtil {
        /**自定义进制(0,1没有加入,容易与o,l混淆)*/
        private static final char[] r = new char[] { 'Q', 'w', 'E', '8', 'a', 'S', '2', 'd', 'Z', 'x', '9', 'c', '7', 'p', 'O', '5', 'i', 'K', '3', 'm', 'j', 'U', 'f', 'r', '4', 'V', 'y', 'L', 't', 'N', '6', 'b', 'g', 'H' };
        /**自动补全组(不能与自定义进制有重复)*/
        private static final char[] b = new char[] { 'q', 'W', 'e', 'A', 's', 'D', 'z', 'X', 'C', 'P', 'o', 'I', 'k', 'M', 'J', 'u', 'F', 'R', 'v', 'Y', 'T', 'n', 'B', 'G', 'h' };
        /**进制长度*/
        private static final int l = r.length;
        /**序列最小长度*/
        private static final int s = 6;

        /**
         * 根据ID生成六位随机码
         * @param num ID
         * @return 随机码
         */
        public static String toSerialNumber(long num) {
            char[] buf = new char[32];
            int charPos = 32;

            while ((num / l) > 0) {
                buf[--charPos] = r[(int) (num % l)];
                num /= l;
            }
            buf[--charPos] = r[(int) (num % l)];
            String str = new String(buf, charPos, (32 - charPos));
            //不够长度的自动随机补全
            if (str.length() < s) {
                StringBuffer sb = new StringBuffer();
                Random rnd = new Random();
                for (int i = 0; i < s - str.length(); i++) {
                    sb.append(b[rnd.nextInt(24)]);
                }
                str += sb.toString();
            }
            return str;
        }

    /**
     * 随机生成验证码（数字+字母）
     * @param len 邀请码长度
     * @return
     */
    public static String generateRandomStr(int len) {
        //字符源，可以根据需要删减
        String generateSource = "23456789abcdefghgklmnpqrstuvwxyz";//去掉1和i ，0和o
        String rtnStr = "";
        for (int i = 0; i < len; i++) {
            //循环随机获得当次字符，并移走选出的字符
            String nowStr = String.valueOf(generateSource.charAt((int) Math.floor(Math.random() * generateSource.length())));
            rtnStr += nowStr;
            generateSource = generateSource.replaceAll(nowStr, "");
        }
        return rtnStr;
    }
}
